home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / xpcom / xpt.py < prev   
Encoding:
Python Source  |  2007-11-12  |  17.4 KB  |  477 lines

  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is the Python XPCOM language bindings.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # ActiveState Tool Corp.
  18. # Portions created by the Initial Developer are Copyright (C) 2000, 2001
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. #   David Ascher <DavidA@ActiveState.com> (original author)
  23. #   Mark Hammond <mhammond@skippinet.com.au>
  24. #
  25. # Alternatively, the contents of this file may be used under the terms of
  26. # either the GNU General Public License Version 2 or later (the "GPL"), or
  27. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. # in which case the provisions of the GPL or the LGPL are applicable instead
  29. # of those above. If you wish to allow use of your version of this file only
  30. # under the terms of either the GPL or the LGPL, and not to allow others to
  31. # use your version of this file under the terms of the MPL, indicate your
  32. # decision by deleting the provisions above and replace them with the notice
  33. # and other provisions required by the GPL or the LGPL. If you do not delete
  34. # the provisions above, a recipient may use your version of this file under
  35. # the terms of any one of the MPL, the GPL or the LGPL.
  36. #
  37. # ***** END LICENSE BLOCK *****
  38.  
  39. """
  40. Program: xpt.py
  41.  
  42. Task: describe interfaces etc using XPCOM reflection.
  43.  
  44. Subtasks:
  45.      output (nearly) exactly the same stuff as xpt_dump, for verification
  46.      output Python source code that can be used as a template for an interface
  47.  
  48. Status: Works pretty well if you ask me :-)
  49.  
  50. Author:
  51.    David Ascher did an original version that parsed XPT files
  52.    directly.  Mark Hammond changed it to use the reflection interfaces,
  53.    but kept most of the printing logic.
  54.  
  55.  
  56. Revision:
  57.  
  58.   0.1: March 6, 2000
  59.   0.2: April 2000 - Mark removed lots of Davids lovely parsing code in favour
  60.                     of the new xpcom interfaces that provide this info.
  61.  
  62.   May 2000 - Moved into Perforce - track the log there!
  63.   Early 2001 - Moved into the Mozilla CVS tree - track the log there!  
  64.  
  65. Todo:
  66.   Fill out this todo list.
  67.  
  68. """
  69.  
  70. import string, sys
  71. import xpcom
  72. import xpcom._xpcom
  73.  
  74. from xpcom_consts import *
  75.  
  76. class Interface:
  77.     def __init__(self, iid):
  78.         iim = xpcom._xpcom.XPTI_GetInterfaceInfoManager()
  79.         try:
  80.             if hasattr(iid, "upper"): # Is it a stringy thing.
  81.                 item = iim.GetInfoForName(iid)
  82.             else:
  83.                 item = iim.GetInfoForIID(iid)
  84.         except xpcom.COMException:
  85.             name = getattr(iid, "name", str(iid))
  86.             print "Failed to get info for IID '%s'" % (name,)
  87.             raise
  88.         self.interface_info = item
  89.         self.namespace = "" # where does this come from?
  90.         self.methods = Methods(item)
  91.         self.constants = Constants(item)
  92.  
  93.     # delegate attributes to the real interface
  94.     def __getattr__(self, attr):
  95.         return getattr(self.interface_info, attr)
  96.  
  97.     def GetParent(self):
  98.         try:
  99.             raw_parent = self.interface_info.GetParent()
  100.             if raw_parent is None:
  101.                 return None
  102.             return Interface(raw_parent.GetIID())
  103.         except xpcom.Exception:
  104.             # Parent interface is probably not scriptable - assume nsISupports.
  105.             if xpcom.verbose:
  106.                 # The user may be confused as to why this is happening!
  107.                 print "The parent interface of IID '%s' can not be located - assuming nsISupports"
  108.             return Interface(xpcom._xpcom.IID_nsISupports)
  109.  
  110.     def Describe_Python(self):
  111.         method_reprs = []
  112.         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  113.         for m in methods:
  114.             method_reprs.append(m.Describe_Python())
  115.         method_joiner = "\n"
  116.         methods_repr = method_joiner.join(method_reprs)
  117.         return \
  118. """class %s:
  119.     _com_interfaces_ = xpcom.components.interfaces.%s
  120.     # If this object needs to be registered, the following 2 are also needed.
  121.     # _reg_clsid_ = "{a new clsid generated for this object}"
  122.     # _reg_contractid_ = "The.Object.Name"\n%s""" % (self.GetName(), self.GetIID().name, methods_repr)
  123.  
  124.     def Describe(self):
  125.         # Make the IID look like xtp_dump - "(" instead of "{"
  126.         iid_use = "(" + str(self.GetIID())[1:-1] + ")"
  127.         s = '   - '+self.namespace+'::'+ self.GetName() + ' ' + iid_use + ':\n'
  128.  
  129.         parent = self.GetParent()
  130.         if parent is not None:
  131.             s = s + '      Parent: ' + parent.namespace + '::' + parent.GetName() + '\n'
  132.         s = s + '      Flags:\n'
  133.         if self.IsScriptable(): word = 'TRUE'
  134.         else: word = 'FALSE'
  135.         s = s + '         Scriptable: ' + word + '\n'
  136.         s = s + '      Methods:\n'
  137.         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  138.         if len(methods):
  139.             for m in methods:
  140.                 s = s + '   ' + m.Describe() + '\n'
  141.         else:
  142.             s = s + '         No Methods\n'
  143.         s = s + '      Constants:\n'
  144.         if self.constants:
  145.             for c in self.constants:
  146.                 s = s + '         ' + c.Describe() + '\n'
  147.         else:
  148.             s = s + '         No Constants\n'
  149.  
  150.         return s
  151.  
  152. # A class that allows caching and iterating of methods.
  153. class Methods:
  154.     def __init__(self, interface_info):
  155.         self.interface_info = interface_info
  156.         try:
  157.             self.items = [None] * interface_info.GetMethodCount()
  158.         except xpcom.Exception:
  159.             if xpcom.verbose:
  160.                 print "** GetMethodCount failed?? - assuming no methods"
  161.             self.items = []
  162.     def __len__(self):
  163.         return len(self.items)
  164.     def __getitem__(self, index):
  165.         ret = self.items[index]
  166.         if ret is None:
  167.             mi = self.interface_info.GetMethodInfo(index)
  168.             ret = self.items[index] = Method(mi, index, self.interface_info)
  169.         return ret
  170.  
  171. class Method:
  172.  
  173.     def __init__(self, method_info, method_index, interface_info = None):
  174.         self.interface_info = interface_info
  175.         self.method_index = method_index
  176.         self.flags, self.name, param_descs, self.result_desc = method_info
  177.         # Build the params.
  178.         self.params = []
  179.         pi=0
  180.         for pd in param_descs:
  181.             self.params.append( Parameter(pd, pi, method_index, interface_info) )
  182.             pi = pi + 1
  183.         # Run over the params setting the "sizeof" params to hidden.
  184.         for p in self.params:
  185.             td = p.type_desc
  186.             tag = XPT_TDP_TAG(td[0])
  187.             if tag==T_ARRAY and p.IsIn():
  188.                 self.params[td[1]].hidden_indicator = 2
  189.             elif tag in [T_PSTRING_SIZE_IS, T_PWSTRING_SIZE_IS] and p.IsIn():
  190.                 self.params[td[1]].hidden_indicator = 1
  191.  
  192.     def IsGetter(self):
  193.         return (self.flags & XPT_MD_GETTER)
  194.     def IsSetter(self):
  195.         return (self.flags & XPT_MD_SETTER)
  196.     def IsNotXPCOM(self):
  197.         return (self.flags & XPT_MD_NOTXPCOM)
  198.     def IsConstructor(self):
  199.         return (self.flags & XPT_MD_CTOR)
  200.     def IsHidden(self):
  201.         return (self.flags & XPT_MD_HIDDEN)
  202.  
  203.     def Describe_Python(self):
  204.         if self.method_index < 3: # Ignore QI etc
  205.             return ""
  206.         base_name = self.name
  207.         if self.IsGetter():
  208.             name = "get_%s" % (base_name,)
  209.         elif self.IsSetter():
  210.             name = "set_%s" % (base_name,)
  211.         else:
  212.             name = base_name
  213.         param_decls = ["self"]
  214.         in_comments = []
  215.         out_descs = []
  216.         result_comment = "Result: void - None"
  217.         for p in self.params:
  218.             in_desc, in_desc_comments, out_desc, this_result_comment = p.Describe_Python()
  219.             if in_desc is not None:
  220.                 param_decls.append(in_desc)
  221.             if in_desc_comments is not None:
  222.                 in_comments.append(in_desc_comments)
  223.             if out_desc is not None:
  224.                 out_descs.append(out_desc)
  225.             if this_result_comment is not None:
  226.                 result_comment = this_result_comment
  227.         joiner = "\n        # "
  228.         in_comment = out_desc = ""
  229.         if in_comments: in_comment = joiner + joiner.join(in_comments)
  230.         if out_descs: out_desc = joiner + joiner.join(out_descs)
  231.  
  232.         return """    def %s( %s ):
  233.         # %s%s%s
  234.         pass""" % (name, ", ".join(param_decls), result_comment, in_comment, out_desc)
  235.  
  236.     def Describe(self):
  237.         s = ''
  238.         if self.IsGetter():
  239.             G = 'G'
  240.         else:
  241.             G = ' '
  242.         if self.IsSetter():
  243.             S = 'S'
  244.         else: S = ' '
  245.         if self.IsHidden():
  246.             H = 'H'
  247.         else:
  248.             H = ' '
  249.         if self.IsNotXPCOM():
  250.             N = 'N'
  251.         else:
  252.             N = ' '
  253.         if self.IsConstructor():
  254.             C = 'C'
  255.         else:
  256.             C = ' '
  257.  
  258.         def desc(a): return a.Describe()
  259.         method_desc = string.join(map(desc, self.params), ', ')
  260.         result_type = TypeDescriber(self.result_desc[0], None)
  261.         return_desc = result_type.Describe()
  262.         i = string.find(return_desc, 'retval ')
  263.         if i != -1:
  264.             return_desc = return_desc[:i] + return_desc[i+len('retval '):]
  265.         return G+S+H+N+C+' '+return_desc+' '+self.name + '('+ method_desc + ');'
  266.  
  267. class Parameter:
  268.     def __init__(self,  param_desc, param_index, method_index, interface_info = None):
  269.         self.param_flags, self.type_desc = param_desc
  270.         self.hidden_indicator = 0 # Is this a special "size" type param that will be hidden from Python?
  271.         self.param_index = param_index
  272.         self.method_index= method_index
  273.         self.interface_info = interface_info
  274.     def __repr__(self):
  275.         return "<param %(param_index)d (method %(method_index)d) - flags = 0x%(param_flags)x, type = %(type_desc)s>" % self.__dict__
  276.     def IsIn(self):
  277.         return XPT_PD_IS_IN(self.param_flags)
  278.     def IsOut(self):
  279.         return XPT_PD_IS_OUT(self.param_flags)
  280.     def IsInOut(self):
  281.         return self.IsIn() and self.IsOut()
  282.     def IsRetval(self):
  283.         return XPT_PD_IS_RETVAL(self.param_flags)
  284.     def IsShared(self):
  285.         return XPT_PD_IS_SHARED(self.param_flags)
  286.     def IsDipper(self):
  287.         return XPT_PD_IS_DIPPER(self.param_flags)
  288.  
  289.     def Describe_Python(self):
  290.         name = "param%d" % (self.param_index,)
  291.         if self.hidden_indicator:
  292.             # Could remove the comment - Im trying to tell the user where that param has
  293.             # gone from the signature!
  294.             return None, "%s is a hidden parameter" % (name,), None, None
  295.         t = TypeDescriber(self.type_desc[0], self)
  296.         decl = in_comment = out_comment = result_comment = None
  297.         type_desc = t.Describe()
  298.         if self.IsIn() and not self.IsDipper():
  299.             decl = name
  300.             extra=""
  301.             if self.IsOut():
  302.                 extra = "Out"
  303.             in_comment = "In%s: %s: %s" % (extra, name, type_desc)
  304.         elif self.IsOut() or self.IsDipper():
  305.             if self.IsRetval():
  306.                 result_comment = "Result: %s" % (type_desc,)
  307.             else:
  308.                 out_comment = "Out: %s" % (type_desc,)
  309.         return decl, in_comment, out_comment, result_comment
  310.  
  311.     def Describe(self):
  312.         parts = []
  313.         if self.IsInOut():
  314.             parts.append('inout')
  315.         elif self.IsIn():
  316.             parts.append('in')
  317.         elif self.IsOut():
  318.             parts.append('out')
  319.  
  320.         if self.IsDipper(): parts.append("dipper")
  321.         if self.IsRetval(): parts.append('retval')
  322.         if self.IsShared(): parts.append('shared')
  323.         t = TypeDescriber(self.type_desc[0], self)
  324.         type_str = t.Describe()
  325.         parts.append(type_str)
  326.         return string.join(parts)
  327.  
  328. # A class that allows caching and iterating of constants.
  329. class Constants:
  330.     def __init__(self, interface_info):
  331.         self.interface_info = interface_info
  332.         try:
  333.             self.items = [None] * interface_info.GetConstantCount()
  334.         except xpcom.Exception:
  335.             if xpcom.verbose:
  336.                 print "** GetConstantCount failed?? - assuming no constants"
  337.             self.items = []
  338.     def __len__(self):
  339.         return len(self.items)
  340.     def __getitem__(self, index):
  341.         ret = self.items[index]
  342.         if ret is None:
  343.             ci = self.interface_info.GetConstant(index)
  344.             ret = self.items[index] = Constant(ci)
  345.         return ret
  346.  
  347. class Constant:
  348.     def __init__(self, ci):
  349.         self.name, self.type, self.value = ci
  350.  
  351.     def Describe(self):
  352.         return TypeDescriber(self.type, None).Describe() + ' ' +self.name+' = '+str(self.value)+';'
  353.  
  354.     __str__ = Describe
  355.  
  356. def MakeReprForInvoke(param):
  357.     tag = param.type_desc[0] & XPT_TDP_TAGMASK
  358.     if tag == T_INTERFACE:
  359.         i_info = param.interface_info
  360.         try:
  361.             iid = i_info.GetIIDForParam(param.method_index, param.param_index)
  362.         except xpcom.Exception:
  363.             # IID not available (probably not scriptable) - just use nsISupports.
  364.             iid = xpcom._xpcom.IID_nsISupports
  365.         return param.type_desc[0], 0, 0, str(iid)
  366.     elif tag == T_ARRAY:
  367.         i_info = param.interface_info
  368.         array_desc = i_info.GetTypeForParam(param.method_index, param.param_index, 1)
  369.         return param.type_desc[:-1] + array_desc[:1]
  370.     return param.type_desc
  371.  
  372.  
  373. class TypeDescriber:
  374.     def __init__(self, type_flags, param):
  375.         self.type_flags = type_flags
  376.         self.tag = XPT_TDP_TAG(self.type_flags)
  377.         self.param = param
  378.     def IsPointer(self):
  379.         return XPT_TDP_IS_POINTER(self.type_flags)
  380.     def IsUniquePointer(self):
  381.         return XPT_TDP_IS_UNIQUE_POINTER(self.type_flags)
  382.     def IsReference(self):
  383.         return XPT_TDP_IS_REFERENCE(self.type_flags)
  384.     def repr_for_invoke(self):
  385.         return (self.type_flags,)
  386.     def GetName(self):
  387.         is_ptr = self.IsPointer()
  388.         data = type_info_map.get(self.tag)
  389.         if data is None:
  390.             data = ("unknown",)
  391.         if self.IsReference():
  392.             if len(data) > 2:
  393.                 return data[2]
  394.             return data[0] + " &"
  395.         if self.IsPointer():
  396.             if len(data)>1:
  397.                 return data[1]
  398.             return data[0] + " *"
  399.         return data[0]
  400.  
  401.     def Describe(self):
  402.         if self.tag == T_ARRAY:
  403.             # NOTE - Adding a type specifier to the array is different from xpt_dump.exe
  404.             if self.param is None or self.param.interface_info is None:
  405.                 type_desc = "" # Dont have explicit info about the array type :-(
  406.             else:
  407.                 i_info = self.param.interface_info
  408.                 type_code = i_info.GetTypeForParam(self.param.method_index, self.param.param_index, 1)
  409.                 type_desc = TypeDescriber( type_code[0], None).Describe()
  410.             return self.GetName() + "[" + type_desc + "]" 
  411.         elif self.tag == T_INTERFACE:
  412.             if self.param is None or self.param.interface_info is None:
  413.                 return "nsISomething" # Dont have explicit info about the IID :-(
  414.             i_info = self.param.interface_info
  415.             m_index = self.param.method_index
  416.             p_index = self.param.param_index
  417.             try:
  418.                 iid = i_info.GetIIDForParam(m_index, p_index)
  419.                 return iid.name
  420.             except xpcom.Exception:
  421.                 return "nsISomething"
  422.         return self.GetName()
  423.  
  424. # These are just for output purposes, so should be
  425. # the same as xpt_dump uses
  426. type_info_map = {
  427.     T_I8                : ("int8",),
  428.     T_I16               : ("int16",),
  429.     T_I32               : ("int32",),
  430.     T_I64               : ("int64",),
  431.     T_U8                : ("uint8",),
  432.     T_U16               : ("uint16",),
  433.     T_U32               : ("uint32",),
  434.     T_U64               : ("uint64",),
  435.     T_FLOAT             : ("float",),
  436.     T_DOUBLE            : ("double",),
  437.     T_BOOL              : ("boolean",),
  438.     T_CHAR              : ("char",),
  439.     T_WCHAR             : ("wchar_t", "wstring"),
  440.     T_VOID              : ("void",),
  441.     T_IID               : ("reserved", "nsIID *", "nsIID &"),
  442.     T_DOMSTRING         : ("DOMString",),
  443.     T_CHAR_STR          : ("reserved", "string"),
  444.     T_WCHAR_STR         : ("reserved", "wstring"),
  445.     T_INTERFACE         : ("reserved", "Interface"),
  446.     T_INTERFACE_IS      : ("reserved", "InterfaceIs *"),
  447.     T_ARRAY             : ("reserved", "Array"),
  448.     T_PSTRING_SIZE_IS   : ("reserved", "string_s"),
  449.     T_PWSTRING_SIZE_IS  : ("reserved", "wstring_s"),
  450. }
  451.  
  452. def dump_interface(iid, mode):
  453.     interface = Interface(iid)
  454.     describer_name = "Describe"
  455.     if mode == "xptinfo": mode = None
  456.     if mode is not None:
  457.         describer_name = describer_name + "_" + mode.capitalize()
  458.     describer = getattr(interface, describer_name)
  459.     print describer()
  460.  
  461. if __name__=='__main__':
  462.     if len(sys.argv) == 1:
  463.         print "Usage: xpt.py [-xptinfo] interface_name, ..."
  464.         print "  -info: Dump in a style similar to the xptdump tool"
  465.         print "Dumping nsISupports and nsIInterfaceInfo"
  466.         sys.argv.append('nsIInterfaceInfo')
  467.         sys.argv.append('-xptinfo')
  468.         sys.argv.append('nsISupports')
  469.         sys.argv.append('nsIInterfaceInfo')
  470.  
  471.     mode = "Python"
  472.     for i in sys.argv[1:]:
  473.         if i[0] == "-":
  474.             mode = i[1:]
  475.         else:
  476.             dump_interface(i, mode)
  477.